#!/usr/bin/env perl

################################################################################
#      cbanalytics.pl
#
#      Copyright 2009 CSS Corporation
#      Author: CSS Labs.
#
#      This program is free software; you can redistribute it and/or modify
#      it under the terms of the GNU General Public License as published by
#      the Free Software Foundation; either version 2 of the License, or
#      (at your option) any later version.
#
#      This program is distributed in the hope that it will be useful,
#      but WITHOUT ANY WARRANTY; without even the implied warranty of
#      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#      GNU General Public License for more details.
#
#      You should have received a copy of the GNU General Public License
#      along with this program; if not, write to the Free Software
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
##################################################################################

#to disable the Buffer output
$| = 1;

#use warnings;		# Must be used in test mode only. This reduce a little process speed
#use diagnostics;	# Must be used in test mode only. This reduce a lot of process speed

#BEGIN {
#my $LIB_PATH = "library_path";
#push @INC, $LIB_PATH;
#};

BEGIN {
use Initialize;
my $config_array = Initialize::initialize('cbanalytics');
my $LIB_PATH = $config_array->{installpath} . "lib/";
push @INC, $LIB_PATH;
};


#-----------------------------------------------------------------------------
# Perl Required Modules: 
#-----------------------------------------------------------------------------
use CGI qw(:standard);
use JawUpdateConfig;
use S3::AWSAuthConnection;

#-----------------------------------------------------------------------------
# User-Defined Perl Modules: 
#-----------------------------------------------------------------------------
use UpdateConfig;
use DownloadLogDB;
use Download;
use Compress;
use Upload;
use CBADBAccess;
use EnableLogging;



# ----- Running variables -----
my $q = CGI->new();
our $IPADD = $q->server_name() . ":" . $q->server_port();
our $conn;
our $bucketName = param('bucket');

# Html Page Generation For View Statistics 
print "Content-type: text/plain\n\n";

#The program starts and checks here for bucket logging

	#Gets access key and secret key from Database table
	our $accessKey = CBADBAccess::getBucketAccessKey( $bucketName);
	our $secretKey = CBADBAccess::getSecretKey($accessKey);
	
	#Connection to Amazon S3
	$conn = S3::AWSAuthConnection->new($accessKey,$secretKey);
	
	#Checks for bucket location and sets calling format of buckets
	my $location_bucket = $conn->get_bucket_location($bucketName);
	if ($location_bucket->location ne 'EU')
	{
	$conn->set_calling_format("PATH");
	}
	
	
	#Checks and Enables logging for given bucket 	
	my $response = $conn->get_bucket_logging($bucketName);
	if(($response->object->data=~ m/\<TargetBucket\>myLogsBucket\<\/TargetBucket\>/) ) {
	my $return_value = EnableLogging::enableLogging($bucketName);
		if ($return_value == 1){
		print "alert";
		exit(0); 
		}
		else{
		print "failed";
		exit(1);
		}
	}
	

	#Checks for database bucket in S3
	our $databaseBucket = lc($accessKey)."logus-cba";
	my $response_exists = $conn->check_bucket_exists( $databaseBucket);
	if($response_exists->http_response->code eq 404){
		#Creates Database bucket in s3 for the first time
		EnableLogging::createTargetBucket( $databaseBucket, $conn);
	}
	
	#Function to update cbanalytics.conf file and create directories
	UpdateConfig::updateConfig( $bucketName);
    
        #Function to initialize the Global Hashes 
	our $config = Initialize::initialize($bucketName);

        #Main function call
        &main(  $bucketName, $conn);
	


#------------------------------------------------------------------------------
# Function:	        Main function
# Parameters:	        bucketName,conn
# Input:		None
# Output:		None
# Return:		None
#------------------------------------------------------------------------------
sub main {
	( $bucketName, $conn ) = @_;
         my  $tag = 0;
       
        #Checks for  awstats .txt  files locally                 
	my $status = &checkConfTxt($bucketName);
	if ( $status == 0 ) {
		#Downloads and Extracts awstats .txt files from S3 and gives lastlogtime of zip file
		our  $timestamp =Download::download( $accessKey, $secretKey, $bucketName);
	}
	
	#Checks for  SQLite  Database file locally		    
	my $return_value = &checkDBfile();
	if ($return_value == 1){
		#Gets lastlogtime for Bucket from SQLite table for given bucket
		my $time = CBADBAccess::getBucketLastLogTime($bucketName);
		
					#If table entry exists
					if ($time ne 0){
					    
					    #Gets targetbucket and targetprefix for given Bucket from S3
					    my $BucketDir   = &getBucketLogDir( $conn, $bucketName);
					    
					    #Downloads logs from targetbucket from lastlogtime
					    DownloadLogDB::downloadLogdb( $accessKey, $secretKey, $BucketDir->{'targetBucket'}, $BucketDir->{'targetPrefix'}, $time, $bucketName);
					}
					else{
					    #If SQlite bucket table entry doesn't exists 
					    &createBucketTableEntry( $accessKey, $secretKey, $conn, $bucketName);
					}
				    # To update Jawstats Config file	
				    JawUpdateConfig::updateJawstatsConfig( $bucketName);
				    #To generate HTML  
				    my $htmlfile = &generateHtml( $bucketName);
				    print "ok";	

	}
	else{
		print "filemissing";
		exit(1);
	}
}

#-----------------------------------------------------------------------------------------------
# Function:	        To Check awstats .txt files locally 
# Parameters:	        bucketName
# Input:		.txt files path 
# Output:		None
# Return:		0 or 1
#-----------------------------------------------------------------------------------------------
sub checkConfTxt {
    ($bucketName) = @_;
    my $chkDir = "$config->{pawtconf}$bucketName/";
    opendir( FDIR, $chkDir ) or die "Can't open $maindir: $!";
    my @folders = readdir(FDIR);
    if ( grep { m|(.*)\.$bucketName\.txt| } @folders ) {
        return 1;
    }
    else { return 0; }
}#End of checkConfTxt

#------------------------------------------------------------------------------
# Function:	        Checks SQLite Database file Exists or Not
# Parameters:	        None
# Input:		Database file path
# Output:		None
# Return:		0 0r 1
#------------------------------------------------------------------------------
sub checkDBfile {
    my $dbname = 'cbanalyticsdb';
    my $chkDir = "$config->{maindir}";
    opendir( FDIR, $chkDir ) or die "Can't open $maindir: $!";
    my @folders = readdir(FDIR);
    if ( grep { m|$dbname| } @folders ) {
        return 1;
    }
    else { return 0; }
}#End of checkDBfile

#-----------------------------------------------------------------------------------------------
# Function:	        To get target bucket,target prefix from S3 for given bucket 
# Parameters:	        conn,bucketNameSDB
# Input:		None
# Output:		None
# Return:		html content
#-----------------------------------------------------------------------------------------------
sub getBucketLogDir {
    ( $conn, $bucketNameSDB ) = @_;
    my $response = $conn->get_bucket_logging($bucketNameSDB);
    $response->object->data =~ m/\<TargetBucket\>(.*)\<\/TargetBucket\>/;
    $hash_ref->{'targetBucket'} = $1;
    $response->object->data =~ m/\<TargetPrefix\>(.*)\<\/TargetPrefix\>/;
    $hash_ref->{'targetPrefix'} = $1;
    return $hash_ref;
}#End of getBucketLogDir

#-------------------------------------------------------------------------------------------
# Function:	        Set lastlogtime value in SQlite Database table and download logs  			
# Parameters:	        Access_key,Secret_access_key,conn,bucketName
# Input:		None
# Output:		None
# Return:		None
#-------------------------------------------------------------------------------------------
sub createBucketTableEntry {
	( $Access_key, $Secret_access_key, $conn, $bucketName) = @_;
	
	my $BucketDir = &getBucketLogDir( $conn, $bucketName );
	if ( $BucketDir->{'targetBucket'} ne '' ) {
		
	    #To enable the Buffer output
	    $| = 0;
	    
	    my $currentTime = 1;
	    
	    if ($timestamp ne 0) {
		
		$currentTime = $timestamp;
	    }
	    #To create SQlite table entry to update target bucket,target prefix and lastlogtime
	    CBADBAccess::updateBucketInfo3( $bucketName, $BucketDir->{'targetBucket'}, $BucketDir->{'targetPrefix'}, $currentTime);
	    
	    #To download logs from S3 target bucket starting from lastlogtime
            DownloadLogDB::downloadLogdb( $Access_key, $Secret_access_key, $BucketDir->{'targetBucket'}, $BucketDir->{'targetPrefix'}, $currentTime, $bucketName);
	}
	else{
		print "fails";
		exit(1);
	}
}#End of createBucketTableEntry

#-----------------------------------------------------------------------------------------------
# Function:	        To generate html content 
# Parameters:	        bucketFile
# Input:		None
# Output:		None
# Return:		html content
#-----------------------------------------------------------------------------------------------
sub generateHtml {
    (my $bucketFile) = @_;
    open( FOUT, ">awstats.$bucketFile.html" );
    my $htmlTxt = "<HTML><HEAD><TITLE>redirect</TITLE>	<META HTTP-EQUIV=\"refresh\" 	CONTENT=\"0 URL=http://$IPADD/awstats/awstats.pl?config=$bucketFile&update=1&status=1&upd=1\"></HEAD></HTML>";
    print FOUT $htmlTxt;
}#End of generateHtml
